/**
 * 
 */
package org.lansir.af.ui;

import org.jivesoftware.smack.util.StringUtils;
import org.lansir.af.R;
import org.lansir.af.gtalk.GtalkApplication;
import org.lansir.af.gtalk.ui.LoginAnim;
import org.lansir.af.gtalk.ui.Settings;
import org.lansir.af.gtalk.utils.GtalkConnectivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.InputFilter;
import android.text.LoginFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;

/**
 * @author 蓝智宏
 *
 */
public class LoginFragment extends CommonFragment {
	private static final String TAG = "LoginFragment";
	private static final int LOGIN_REQUEST_CODE = 1;
	private boolean mIsResult;
	private EditText etLoginUserName;
	private EditText etLoginUserPassword;
	private Button btnLogin;
	private CheckBox cbAutoLogin;
	
	private final JidTextWatcher mJidTextWatcher = new JidTextWatcher();
	private final PasswordTextWatcher mPasswordTextWatcher = new PasswordTextWatcher();
	private boolean mValidJid;
	private boolean mValidPassword;
	private boolean mChangeUser = false;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);		
		Bundle bundle = this.getArguments();
		if(bundle != null && bundle.containsKey("ChangeUser"))
			mChangeUser = bundle.getBoolean("ChangeUser", false);
		Log.v(TAG, "LoginFragment");
		this.setHasOptionsMenu(true);
	}
	
	

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View viewRoot = inflater.inflate(R.layout.login, null);
		etLoginUserName = (EditText)viewRoot.findViewById(R.id.etLoginUserName);
		etLoginUserPassword = (EditText)viewRoot.findViewById(R.id.etLoginUserPassword);
		cbAutoLogin = (CheckBox) viewRoot.findViewById(R.id.cbLoginAutoLogin);
		btnLogin = (Button)viewRoot.findViewById(R.id.btnLogin);
		
		InputFilter[] orgFilters = etLoginUserName.getFilters();
		InputFilter[] newFilters = new InputFilter[orgFilters.length + 1];
		int i;
		for (i = 0; i < orgFilters.length; i++)
			newFilters[i] = orgFilters[i];
		newFilters[i] = new LoginFilter.UsernameFilterGeneric();
		etLoginUserName.setFilters(newFilters);
		etLoginUserName.addTextChangedListener(mJidTextWatcher);
		etLoginUserPassword.addTextChangedListener(mPasswordTextWatcher);
		btnLogin.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				configureAccount();
				Intent i = new Intent(getActivity(), LoginAnim.class);
				startActivityForResult(i, LOGIN_REQUEST_CODE);
			}		
		});
		cbAutoLogin.setOnCheckedChangeListener(new OnCheckedChangeListener(){
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				confiureAutoLogin();
			}			
		});
		loadAccount();
//		mTextView = (TextView) viewRoot.findViewById(R.id.log_as_msg);
		return viewRoot;
	}



	@Override
	public void onStart() {
		super.onStart();
		if (mGtalkApplication.isAccountConfigured() && !mIsResult && GtalkConnectivity.isConnected(getActivity().getApplicationContext()) && cbAutoLogin.isChecked() && !mChangeUser) {
			Intent i = new Intent(getActivity(), LoginAnim.class);
			startActivityForResult(i, LOGIN_REQUEST_CODE);
			mIsResult = false;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == LOGIN_REQUEST_CODE) {
			mIsResult = true;
			if (resultCode == Activity.RESULT_OK) {
				startActivity(new Intent(getActivity(), ContactListActivity.class));
				finish();
			} else if (resultCode == Activity.RESULT_CANCELED) {
				if (data != null) {
					String tmp = data.getExtras().getString("message");
					Toast.makeText(getActivity(), tmp, Toast.LENGTH_SHORT).show();
					
				}
			}
		}
	}
	
	

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.login, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public final boolean onOptionsItemSelected(MenuItem item) {
		boolean result;
		switch (item.getItemId()) {
		case R.id.login_menu_settings:

			startActivity(new Intent(getActivity(), Settings.class));
			result = true;
			break;
		default:
			result = false;
			break;
		}
		return result;
	}

	
	
	/**
	 * Store the account in the settings.
	 */
	private void configureAccount() {
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
		SharedPreferences.Editor edit = settings.edit();
		edit.putString(GtalkApplication.ACCOUNT_USERNAME_KEY, etLoginUserName.getText().toString());
		edit.putString(GtalkApplication.ACCOUNT_PASSWORD_KEY, etLoginUserPassword.getText().toString());
		edit.commit();
	}
	
	private void confiureAutoLogin(){
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
		SharedPreferences.Editor edit = settings.edit();
		edit.putBoolean(GtalkApplication.ACCOUNT_AUTO_LOGIN, cbAutoLogin.isChecked());
		edit.commit();
	}
	
	private void loadAccount(){
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
		etLoginUserName.setText(settings.getString(GtalkApplication.ACCOUNT_USERNAME_KEY, ""));
		etLoginUserPassword.setText(settings.getString(GtalkApplication.ACCOUNT_PASSWORD_KEY, ""));
		cbAutoLogin.setChecked(settings.getBoolean(GtalkApplication.ACCOUNT_AUTO_LOGIN, false));
	}
	
	/**
	 * Check that the username is really a JID.
	 * 
	 * @param username
	 *            the username to check.
	 */
	private void checkUsername(String username) {
		String name = StringUtils.parseName(username);
		String server = StringUtils.parseServer(username);
		if (TextUtils.isEmpty(name) || TextUtils.isEmpty(server)) {
			mValidJid = false;
		} else {
			mValidJid = true;
		}
	}

	/**
	 * Check password.
	 * 
	 * @param password
	 *            the password to check.
	 */
	private void checkPassword(String password) {
		if (password.length() > 0)
			mValidPassword = true;
		else
			mValidPassword = false;
	}
	
	/**
	 * Text watcher to test the existence of a password.
	 */
	private class PasswordTextWatcher implements TextWatcher {

		/**
		 * Constructor.
		 */
		public PasswordTextWatcher() {
		}

		@Override
		public void afterTextChanged(Editable s) {
			checkPassword(s.toString());
			btnLogin.setEnabled(mValidJid && mValidPassword);
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
		}
	}

	/**
	 * TextWatcher to check the validity of a JID.
	 */
	private class JidTextWatcher implements TextWatcher {

		/**
		 * Constructor.
		 */
		public JidTextWatcher() {
		}

		@Override
		public void afterTextChanged(Editable s) {
			checkUsername(s.toString());
			btnLogin.setEnabled(mValidJid && mValidPassword);
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
		}
	}
}
